package com.example.everying.mapper.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.everying.model.entity.user.UserBalanceEntity;

import java.math.BigDecimal;

public interface UserBalanceMapper extends BaseMapper<UserBalanceEntity> {
    /**
     * MyBatis-Plus 乐观锁扣减
     * @return 是否更新成功
     */
    default boolean mpDeductBalance(String userId, BigDecimal amount) {
        // 1. 查询当前数据（带版本号）
        UserBalanceEntity balance = selectOne(
                new LambdaQueryWrapper<UserBalanceEntity>()
                        .eq(UserBalanceEntity::getUserId, userId));

        if (balance == null || balance.getAvailableAmount().compareTo(amount) < 0 ) {
            return false;
        }
        if (amount == null || amount.compareTo(BigDecimal.ZERO)  <= 0) {
            throw new IllegalArgumentException("扣减金额必须为正数");
        }
        // 2. 构建更新条件（版本号校验）
        int rows = update(null,
                new LambdaUpdateWrapper<UserBalanceEntity>()
                        .eq(UserBalanceEntity::getUserId, userId)
                        .eq(UserBalanceEntity::getVersion, balance.getVersion())
                        .ge(UserBalanceEntity::getAvailableAmount, amount) // 余额充足条件
                        .set(UserBalanceEntity::getLastAmount, balance.getAvailableAmount())
                        .set(UserBalanceEntity::getAvailableAmount, balance.getAvailableAmount().subtract(amount))  // 安全减法
                        .set(UserBalanceEntity::getVersion, balance.getVersion()  + 1)); // 版本号+1

        return rows > 0;
    }
    /**
     * 乐观锁增加余额
     * @param userId 用户ID
     * @param amount 增加金额（正数）
     * @return 是否更新成功
     */
    default boolean mpAddBalance(String userId, BigDecimal amount) {
        // 1. 查询当前数据（带版本号）
        UserBalanceEntity balance = selectOne(
                new LambdaQueryWrapper<UserBalanceEntity>()
                        .eq(UserBalanceEntity::getUserId, userId));

        // 2. 如果用户余额记录不存在，则初始化
        if (balance == null) {
            UserBalanceEntity newBalance = new UserBalanceEntity();
            newBalance.setUserId(userId);
            newBalance.setAvailableAmount(amount);
            newBalance.setLastAmount(BigDecimal.valueOf(0));
            return insert(newBalance) > 0;
        }

        // 3. 乐观锁更新
// 3. 乐观锁更新（安全写法）
        int rows = update(null,
                new LambdaUpdateWrapper<UserBalanceEntity>()
                        .eq(UserBalanceEntity::getUserId, userId)
                        .eq(UserBalanceEntity::getVersion, balance.getVersion())
                        .set(UserBalanceEntity::getLastAmount, balance.getAvailableAmount())
                        .set(UserBalanceEntity::getAvailableAmount, balance.getAvailableAmount().add(amount))   // 使用BigDecimal.add() 方法
                        .set(UserBalanceEntity::getVersion, balance.getVersion()  + 1)); // 直接Java计算版本号

        return rows > 0;
    }
}